<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2-处理ajax响应</title>
    <style>
        #box {
            width: 200px;
            height: 200px;
            border: 1px solid #666;
        }
    </style>
</head>

<body>
    <button id="textBtn">AJAX 获取Text</button>
    <button id="jsonBtn">AJAX 获取JSON</button>

    <div id="box"></div>

</body>
<script>
    document.querySelector('#textBtn').onclick = () => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', 'http://127.0.0.1:8081/text-server')
        xhr.send()

        // 绑定状态改变的监听
        xhr.onreadystatechange = () => {
            console.log('onreadystatechange readyState', xhr.readyState)
            // 如果请求完成，才去取数据
            if (xhr.readyState == 4) {
                // 响应状态码
                console.log(xhr.status)
                // 响应头
                console.log(xhr.getResponseHeader('Content-Type'))
                // 响应体
                console.log(xhr.responseText)

                // 显示响应体
                document.querySelector('#box').innerHTML = xhr.responseText
            }
        }
    }

    document.querySelector('#jsonBtn').onclick = () => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', 'http://127.0.0.1:8081/json-server')
        xhr.send()

        // 绑定状态改变的监听
        xhr.onreadystatechange = () => {
            console.log('onreadystatechange readyState', xhr.readyState)
            // 如果请求完成，才去取数据
            if (xhr.readyState == 4) {
                // 响应状态码
                console.log(xhr.status)
                // 响应头
                console.log(xhr.getResponseHeader('Content-Type'))
                // 响应体
                console.log(xhr.responseText)

                // 显示响应体
                document.querySelector('#box').innerHTML = xhr.responseText
            }
        }
    }



</script>

</html>